package com.manlitech.manlichat.service.nettywebsocket;

import com.manlitech.manlichat.base.netty.message.container.MessageHandler;
import com.manlitech.manlichat.base.netty.util.MessageSendUtil;
import com.manlitech.manlichat.dao.ImUserDao;
import com.manlitech.manlichat.dto.ImUser;
import com.manlitech.manlichat.enums.ResultEnums;
import com.manlitech.manlichat.pojo.SessionInfo;
import com.manlitech.manlichat.pojo.nettywebsocket.AuthMessage;
import com.manlitech.manlichat.service.ImUserService;
import com.manlitech.manlichat.util.ResultUtil;
import com.manlitech.manlichat.util.SessionInfoUtils;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class AuthMessageHandler implements MessageHandler<AuthMessage> {

    @Autowired
    MessageSendUtil messageSendUtil;

    @Autowired
    SessionInfoUtils sessionInfoUtils;

    @Autowired
    ImUserService imUserService;

    @Autowired
    ImUserDao imUserDao;

    @Override
    public void execute(Channel channel, AuthMessage message) throws Exception{
        String jwtToken = message.getJwtToken();
        //判断JWT是否可用
        String uniqueKey = sessionInfoUtils.getSessionInfoByAccessToken(jwtToken);
        SessionInfo sessionInfo = new SessionInfo();
        sessionInfo.setBranchId(1);
        if(uniqueKey != null){

            //判断有没有存入数据库
            ImUser hasImUser = imUserDao.createLambdaQuery().andEq("uniquekey",uniqueKey).single();
            if(hasImUser != null){
                hasImUser.setStatus("online");
                imUserService.updateById(hasImUser);
            }else{
                hasImUser = new ImUser();
                hasImUser.setAvatar(null);
                hasImUser.setSign("这人很懒没有签名");
                hasImUser.setStatus("online");
                hasImUser.setUsername(uniqueKey);
                hasImUser.setUniquekey(uniqueKey);
                hasImUser.setRemarkname(hasImUser.getUsername());
                imUserService.save(hasImUser);
            }
            //响应客户端
            messageSendUtil.binUidAndChannelId(uniqueKey,channel.id());
            messageSendUtil.responseTheRequest(channel, ResultUtil.success(hasImUser));
        }else{
            messageSendUtil.responseTheRequest(channel, ResultUtil.error(ResultEnums.ERROR_GET_UNIQUEKEY.getCode(), ResultEnums.ERROR_GET_UNIQUEKEY.getMsg()));
        }
    }

    @Override
    public String getType() {
        return AuthMessage.TYPE;
    }
}
